import _ from 'lodash';
import BW from './bwCommon';
import urls from './apiUrls';

/**
 * [request Ajax 公共库]
 * @param  {[String]} apiName   [api 缩写名]
 * @param  {[Object]} paramsObj [Post 参数]
 */
const jsonpRequest = function jsonpRequest(apiName, paramsObj) {
  paramsObj = paramsObj || {}
  if (_.isUndefined(urls[apiName])) {
    BW.Toast('接口地址未注册')
    return;
  }
  let usrInfo = this.$store.getters.getUsrInfo ? this.$store.getters.getUsrInfo : ''
  return new Promise((resolve, reject) => {
    this.$store.commit('updateLoadingStatus', true)
    wVue.$jsonp(urls[apiName], Object.assign(paramsObj, {
      login_user_info: JSON.stringify(usrInfo),
      callbackQuery: 'callback', // 回调函数键名
      callbackName: 'jsonpCallback' // 回调函数值名
    })).then(res => {
      // 返回数据 json， 返回的数据就是json格式
      if (res.Status === 552) {      // 需要去登录
        let redirect = location.href
        location.href = res.Result.Url + '?url=' + wVue.Base64.encode(encodeURI(redirect))
        reject(res)
      } else if (res.Status !== 200) {
        this.$store.commit('updateLoadingStatus', false)
        BW.Toast(res.Msg)
        reject(res)
      } else {
        resolve(res)
        let newInfo = {}
        if (typeof (res.Result.LoginUserInfo) !== 'undefined') {
          if (usrInfo !== '') newInfo = usrInfo
          wVue.$store.commit('setUsrInfo', Object.assign(newInfo, res.Result.LoginUserInfo))
        }
      }
    }).catch(err => {
      this.$store.commit('updateLoadingStatus', false)
      BW.Toast(err)
      reject(err)
    })
  });
};

export default jsonpRequest;
